package com.lanou.myapp.funny.videofunny;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.lanou.myapp.R;

import java.io.IOException;


/**
 * Created by dllo on 16/1/26.
 */
public class VideoActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener {
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer mediaPlayer;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_activity);
        Intent intent = getIntent();
        url = intent.getStringExtra("key");
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView_video);
        //给SurfaceView添加CallBack监听
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);


    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
// 当SurfaceView中的Surface被创建的时候被调用

        //然后指定需要播放文件的路径，初始化MediaPlayer
        //在指定了MediaPlayer播放的容器后，我们就可以使用prepare或者prepareAsync来准备播放了

        try {
            mediaPlayer.setDataSource(VideoActivity.this, Uri.parse(url));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        try {
//            mediaPlayer.setDataSource(VideoActivity.this, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.intro));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //在这里我们指定MediaPlayer在当前的Surface中进行播放
        mediaPlayer.setDisplay(surfaceHolder);
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // 当Surface尺寸等参数改变时触发
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // 当MediaPlayer播放完成后触发
//        mediaPlayer = MediaPlayer.create(SurfaceDemo.this,Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.intro));

        mediaPlayer.start();
    }

}

